/**
 * Created by   :Wangshuzhong
 * Created time :2017-04-06
 * File explain :交易账务--本年度交易账务
 */

require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    bootTable: ["bootstrap-table-dist/dist/js/bootstrap-table"],
    bootTableCN: ["bootstrap-table-dist/dist/locale/bootstrap-table-zh-CN"],
    comConfig: ["../common/js/common-config"],
    echart:["//cdn.bootcss.com/echarts/3.5.0/echarts"]
  }
});
require(["jquery"],function() {
  require(["bootTable"], function () {
    require(["echart","zui", "layer", "bootTableCN", "comConfig"], operationCodeFun)
  })
})
function operationCodeFun(echarts) {
  // 由于使用require框架整合，我们需要为layer.js配置读取css文件的路径
  layer.config({
    path: "../../libs/layer/"
  })

  //变量声明
  var QHConfig = $("body").data("config");
  var nowYear = null;//当前年份
  var allMonthData = null;//当前年度月交易明细所有数据
  var myChart = echarts.init($("#id-line-pic")[0]);//实例化echarts折线图对象

  //end

  //页面初始化
  getYears();//获取年份
  getMonthTradingAccounts(nowYear);//获取交易账务（月数据）和本月数据,获取折线图数据
  allMonthTableRender(nowYear);//交易账务月数据表格渲染
  tradingAccountsProject(nowYear);//交易账务（项目）

  //end

  //事件绑定
  //改变年份，页面的内容随着年分变
  $("#id-year-choose").on("change",function(){
    nowYear = $(this).val();
    getMonthTradingAccounts(nowYear);
  })
  //点击查看更多交易账务（项目）
  $(".cmn-look-more").on("click",lookMoreProjectAccount);
  //end

  //to do 其他功能函数
  /*
   * 获取当前供应商的入驻时间
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function getYears(){
    $.ajax(tokenAjax({
      url:QHConfig.url.getYears,
      async:false,
      dataType:"json",
      success:function(data){
        var _data=data.data;
        var oHtml="";

        if(_data) {
          for(var i=0;i<_data.length;i++){
            oHtml += `<option value="${_data[i]}">${_data[i]}</option>`;
          };
        }
        $("#id-year-choose").html(oHtml);
      }
    }));
    nowYear = $("#id-year-choose").val();
  }
  /*
   * 根据年限获取月交易数据和交易账务（项目），进来默认为今年，表格渲染
   * @params year,年份
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function getMonthTradingAccounts(year) {
    var ajaxData = {date : year};//请求交易账务月数据需要传的参数

    $.ajax(tokenAjax({
      url:QHConfig.url.getCarryOver,
      async:false,
      data:ajaxData,
      dataType:"json",
      success:renderByYear
    }));
    $("#id-user-account-table").bootstrapTable("refresh");
    $("#id-user-project-table").bootstrapTable("refresh");
  }
  /*
   * 根据年限获取月交易数据
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function renderByYear(data){
    var thisMonth=data.data.carryoverThisMonth;//当月数据
    var chooseYear = $("#id-year-choose").val();//选择的年
    var todayYear = new Date().getFullYear();//今年
    var nowMonth = new Date().getMonth() + 1;//这个月
    var thisYear = data.data.list;//选择年份的所有月数据
    var _yearMonth = null;//当月的年份和月份

    allMonthData = thisYear;//本年度所有月交易数据
    if(thisMonth) {
      //判断当月日期
      if(thisMonth.operationDate) {
        _yearMonth = thisMonth.operationDate.split("-");//获取当月的年份和月份
      }else {
        _yearMonth = [chooseYear,nowMonth];//获取今年当月的年份和月份
      };
      //渲染本月交易数据
      $(".cmn-thisMonth-lastUnpaid").html(getMillions(thisMonth.lastUnpaid));//上月结转
      $(".cmn-thisMonth-currentTotal").html(getMillions(thisMonth.currentTotal));//本月应收
      $(".cmn-thisMonth-currentHaspaid").html(getMillions(thisMonth.currentHaspaid));//本月实收
      $(".cmn-thisMonth-notReceipt").html(getMillions(thisMonth.notReceipt));//本月未收
    }else {
      _yearMonth = [chooseYear,nowMonth];//获取当月的年份和月份
      //渲染本月交易数据
      $(".cmn-thisMonth-lastUnpaid").html("-");//上月结转
      $(".cmn-thisMonth-currentTotal").html("-");//本月应收
      $(".cmn-thisMonth-currentHaspaid").html("-");//本月实收
      $(".cmn-thisMonth-notReceipt").html("-");//本月未收
    }

    var thisMonthStart = _yearMonth[0] + "年" + _yearMonth[1] + "月01日";//当月的开始时间
    var thisMonthEnd = _yearMonth[0] + "年" + _yearMonth[1] + "月" + getLastDay(_yearMonth[0],_yearMonth[1]) + "日";//当月的结束时间

    if(chooseYear == todayYear) {
      $(".cmn-thisMonth-data").html(`（${thisMonthStart}-至今）`);
    }else {
      $(".cmn-thisMonth-data").html(`（${thisMonthStart}-${thisMonthEnd}）`);
    }
    $(".cmn-allMonth-data").html(`（${chooseYear}年01月01日-${chooseYear}年12月31日）`);//自然年度时间
    //渲染折线图
    renderLinePic(thisYear);
  }
  /*
   * 获取本月开始时间
   * @params time,时间字符串“2017-04”
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function getTurnToTime(time) {
    var oTime = time.split("-")
    return oTime[0]+"年"+oTime[1]+"月01日";
  }
  /*
   * 元转万元，保留两位小数
   * @params val,金额（元）
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function getMillions(val) {
    if(val){
      val = QHConfig.turnMoney(val/10000,2);
    }else {
      val = "0.00";
    }
    return val;
  }
  /*
   * 折线图所需数字
   * @params val,金额（元）
   * @author Wangshuzhong
   * @Date   2017/06/23
   */
  function turnNeedNumber(val) {
    if(val){
      val = val/10000;
    }else {
      val = 0;
    }
    return val;
  }
  /*
   * 年度交易账务（月数据）表格渲染
   * @params year,年度
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function allMonthTableRender(year){
    $("#id-user-account-table").bootstrapTable({
      url:QHConfig.url.getCarryOver,
      queryParams:function(params){
        params.derection="asc";
        params.sort="id";
        params.date = year;
        return params;
      },
      responseHandler:function(res){
        return QHConfig.BSTTableResHandler(res,resDataAllMonthFmt);
      },
      ajax:tableAjax,
      onLoadSuccess:function(data){
        var lookMonthDetail = $("#id-user-account-table .cmn-active-breadcrumb");

        //点击查看详情，跳转到当月交易明细页面
        lookMonthDetail.on("click",function(){
          var index=$(this).parent().parent()[0].rowIndex-1;//当前行序号
          var thisData=allMonthData[index].operationDate;//获取当月具体日期

          thisMonthAccountDetail(thisData);//弹窗查看月交易明细
        })
      }
    });
  }
  //月数据表格数据渲染和格式转换,$data:当前行对象
  function resDataAllMonthFmt($data) {
    var yearMonth = $data.operationDate.split("-");
    $data.year = yearMonth[0];
    $data.month = parseInt(yearMonth[1]);
    $data.lastUnpaid = getMillions($data.lastUnpaid);
    $data.currentAdjust = $data.currentAdjust == 0?"无":$data.currentAdjust;
    $data.currentTotal = getMillions($data.currentTotal);
    $data.currentHaspaid = getMillions($data.currentHaspaid);
    $data.notReceipt = getMillions($data.notReceipt);
    $data.event = "<span class='cmn-active-breadcrumb'>查看详情</span>";
  }
  /*
   * 获取某月的最后一天
   * @param year,年份
   * @param month,月份
   * @author wangshuzhong
   * @Date   2017/4/06
   * */
  function getLastDay(year,month) {
    var new_year = year;    //取当前的年份
    var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）
    if(month>12) {
      new_month -=12;        //月份减
      new_year++;            //年份增
    }
    var new_date = new Date(new_year,new_month,1);                //取当年当月中的第一天
    return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期
  }
  /*
   * 年度交易账务（月数据）表格渲染
   * @params date,时间“2017-04”
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function thisMonthAccountDetail(date) {
    layer.open({
      title: false,
      shade: 0.8,
      move:false,
      closeBtn:0,
      resize:false,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: `../mdu-month-trade-receivable/mdu-month-trade-receivable.html?operationDate=${date}`
    })
  }
  /*
   * 年度交易账务（项目）表格渲染
   * @params year,年度
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function tradingAccountsProject(year){
    $("#id-user-project-table").bootstrapTable({
      url:QHConfig.url.getCarryOverProject,
      queryParams:function(params) {
        params.derection="asc";
        params.sort="id";
        params.date = year;
        params.pageNum = 1;
        params.pageSize = 5;
        return params;
      },
      ajax:tableAjax,
      responseHandler:function(res) {
        return QHConfig.BSTTableResHandler(res,resDataProjectFmt);
      },
      onLoadSuccess:function() {
        var allTr = $("#id-user-project-table tbody tr");

        for(var i=0;i<allTr.length;i++) {
          allTr.eq(i).find("td").eq(1).addClass("cmn-project-text");
          allTr.eq(i).find("td").eq(2).addClass("cmn-company-text");
        }
      }
    })
  }
  //交易账务（项目）表格数据渲染和格式转换,$data:当前行对象，i:当前索引
  function resDataProjectFmt($data,i) {
    $data.index = i + 1;
    $data.lastUnpaid = getMillions($data.lastUnpaid);
    $data.currentTotal = getMillions($data.currentTotal);
    $data.currentHaspaid = getMillions($data.currentHaspaid);
    $data.notReceipt = getMillions($data.notReceipt);
    $data.currentAdjust = $data.currentAdjust == 0?"无":$data.currentAdjust;
  }
  /*
   * 查看本年度更多交易账务（项目）
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function lookMoreProjectAccount() {
    layer.open({
      title: false,
      shade: 0.8,
      move:false,
      closeBtn:0,
      resize:false,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: `../mdu-trade-account-project/mdu-trade-account-project.html?operationDate=${nowYear}`
    })
  }
  /*
   * 渲染折线图表
   * @params list,折线图所需要的数据
   * @author Wangshuzhong
   * @Date   2017/04/06
   */
  function renderLinePic(list) {
    var lastUnpaid = [];//上月结转数据数组
    var currentTotal = [];//本月应收数据数组
    var currentHaspaid = [];//本月实收数据数组
    var notReceipt = [];//本月未收数据数组

    if(list) {
      for(var i=0;i<list.length;i++) {
        lastUnpaid.push(turnNeedNumber(list[i].lastUnpaid));
        currentTotal.push(turnNeedNumber(list[i].currentTotal));
        currentHaspaid.push(turnNeedNumber(list[i].currentHaspaid));
        notReceipt.push(turnNeedNumber(list[i].notReceipt));
      }
    };

    var option = {
      tooltip : setToolTips(lastUnpaid,currentTotal,currentHaspaid,notReceipt),//提示窗
      lineStyle : {
        color : ['#fff']
      },//线条颜色
      xAxis : setXParams(),//横轴
      yAxis : setYParams(),//纵轴
      series : renderDataForLine(currentTotal)//画折线图所需参数
    };
    myChart.setOption(option);//调用开始画
  }
  /*
   * 折线图横坐标参数设置
   * @author Wangshuzhong
   * @Date   2017/04/10
   */
  function setXParams(){
    var arr = [];
    var obj = {
      type : 'category',
      boundaryGap : false,
      name:"月份",
      data : ['1','2','3','4','5','6','7','8','9','10','11','12'],
      axisTick:false,
      splitLine:false,
      show : true,
      nameTextStyle :{
        color: '#283950'
      },
      axisLabel:{
        textStyle: {color :'#283950'}
      },
      axisLine : {
        show: true,
        lineStyle :{
          color: '#358ED7'
        }
      },
      splitArea :{
        show : true,
        areaStyle : {
          color : '#358ED7'
        }
      }
    };

    arr.push(obj);
    return arr;
  }
  /*
   * 折线图纵坐标参数设置
   * @author Wangshuzhong
   * @Date   2017/04/10
   */
  function setYParams(){
    var arr = [];
    var obj = {
      type : 'value',
      name : "应收货款（万元）",
      axisTick:false,
      splitLine:false,
      boundaryGap : [0,1],
      nameTextStyle :{
        color: '#283950'
      },
      axisLabel:{
        textStyle: {color :'#283950'}
      },
      axisLine : {
        show: true,
        lineStyle :{
          color: '#358ED7'
        }
      },
      splitArea :{
        show : true,
        areaStyle : {
          color : '#358ED7'
        }
      }
    };

    arr.push(obj);
    return arr;
  }
  /*
   * 折线图数据渲染
   * @param  data,需要的数据
   * @author Wangshuzhong
   * @Date   2017/04/10
   */
  function renderDataForLine(needData){
    var arr = [];
    var obj = {
      name:'本月应收款',
      type:'line',
      smooth:true,
      symbol :'image://../../common/img/private/cricle.png',
      symbolSize : 8,
      itemStyle: {normal: {
        areaStyle: {type: 'default',color:'#5DA5DF'},
        lineStyle : {color:'#8CBFE8'},
        color :'#fff'
      }},
      data:needData
    };

    arr.push(obj);
    return arr;
  }
  /*
   * 折线图提示框参数设置
   * @param  a,上月结转数组
   * @param  b,本月应收数组
   * @param  c,本月实收数组
   * @param  d,本月未收数组
   * @author Wangshuzhong
   * @Date   2017/04/10
   */
  function setToolTips(a,b,c,d){
    return {
      trigger: 'axis',
      backgroundColor: '#fff',
      textStyle: {
        color: '#358ED7'
      },
      formatter: function (params, ticket, callback) {
        var res = params[0].name + "月交易数据<br/>";//悬浮标题
        var index = parseInt(params[0].dataIndex);

        res += `上月结转额:&nbsp;&nbsp;${turnGetMoney(a[index])}<br/>
          本月应收货款:&nbsp;&nbsp;${turnGetMoney(b[index])}<br/>
          本月实收货款:&nbsp;&nbsp;${turnGetMoney(c[index])}<br/>
          本月未收货款:&nbsp;&nbsp;${turnGetMoney(d[index])}
          `;//鼠标悬浮显示的字符串内容
        setTimeout(function () {
          // 仅为了模拟异步回调
          callback(ticket, res);
        }, 500)
        return 'loading...';
      }
    };
  }
  function turnGetMoney(val) {
    if(val) {
      return QHConfig.turnMoney(val,2) + "万元";
    }else{
      return "0.00万元";
    }
  }
  //end
}